<template>
  <div class="min-h-screen bg-[#f5f7fa] p-6">
    <!-- 页面标题 -->
    <div class="mb-6">
      <h2 class="text-2xl font-light text-[#303133]">考试中心</h2>
      <p class="mt-1 text-sm text-[#909399]">在这里你可以参加各种考试和测验</p>
    </div>

    <!-- 筛选区域 -->
    <div class="mb-6">
      <el-input
        v-model="filters.title"
        placeholder="搜索考试名称"
        class="w-full max-w-xl"
        clearable
        @clear="handleSearch"
        @keyup.enter="handleSearch"
      >
        <template #prefix>
          <el-icon><Search /></el-icon>
        </template>
        <template #append>
          <el-button :icon="Search" @click="handleSearch"> 搜索 </el-button>
        </template>
      </el-input>
    </div>

    <!-- 考试列表 -->
    <div
      class="grid grid-cols-1 gap-6 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4"
    >
      <exam-item
        v-for="exam in examList"
        :key="exam.id"
        :exam="exam"
        @click="handleExamClick(exam)"
      />
    </div>

    <!-- 分页 -->
    <div class="mt-6 flex justify-center">
      <div class="flex items-center space-x-4 text-sm">
        <!-- 总数显示 -->
        <span class="text-[#909399]">共 {{ total }} 条</span>

        <!-- 上一页 -->
        <button
          class="text-[#606266] hover:text-[#409EFF] disabled:cursor-not-allowed disabled:text-[#C0C4CC]"
          :disabled="currentPage <= 1"
          @click="handleCurrentChange(currentPage - 1)"
        >
          <
        </button>

        <!-- 页码 -->
        <div class="flex items-center space-x-1">
          <template v-for="page in pageNumbers" :key="page">
            <button
              v-if="page !== '...'"
              class="px-2 text-[#606266]"
              :class="
                page === currentPage ? 'text-[#409EFF]' : 'hover:text-[#409EFF]'
              "
              @click="handleCurrentChange(page)"
            >
              {{ page }}
            </button>
            <span v-else class="px-1 text-[#606266]"> ... </span>
          </template>
        </div>

        <!-- 下一页 -->
        <button
          class="text-[#606266] hover:text-[#409EFF] disabled:cursor-not-allowed disabled:text-[#C0C4CC]"
          :disabled="currentPage >= totalPages"
          @click="handleCurrentChange(currentPage + 1)"
        >
          >
        </button>

        <!-- 前往页面输入框 -->
        <div class="flex items-center space-x-2">
          <span class="text-[#606266]">前往</span>
          <input
            v-model.number="jumpPage"
            type="number"
            class="w-12 border-b border-[#DCDFE6] px-1 text-center text-[#606266] outline-none focus:border-[#409EFF]"
            min="1"
            :max="totalPages"
            @keyup.enter="handleJumpPage"
          />
          <span class="text-[#606266]">页</span>
        </div>
      </div>
    </div>

    <!-- 无数据显示 -->
    <el-empty v-if="examList.length === 0" description="暂无考试数据" />
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch } from 'vue'
import { Search } from '@element-plus/icons-vue'
import ExamItem from './examItem.vue'
// 导入默认图片
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/store/modules/user'
import { useRouter } from 'vue-router'
import { getGradeExamList } from '@/api/user/exam'

const store = useUserStore()
const router = useRouter()

// 搜索和筛选

const filters = reactive({
  pageNum: 1,
  pageSize: 10,
  title: '',
})

// 分页
const currentPage = ref(1)
const pageSize = ref(12)
const total = ref(10)
const pageNumbers = ref([1, 2, 3, 4, 5])
const totalPages = ref(1)
const jumpPage = ref(1)

// 模拟考试数据
const examList = ref([])

// 处理搜索
const handleSearch = () => {
  currentPage.value = 1
  fetchExamList()
}

// 重置筛选条件
const resetFilters = () => {
  // 重置所有筛选条件为默认值
  filters.title = ''
  filters.pageNum = 1
  filters.pageSize = 10
  
  // 重置分页相关参数
  currentPage.value = 1
  pageSize.value = 12
  
  // 重新获取数据
  fetchExamList()
  
  // 提示用户已重置筛选条件
  ElMessage.success('筛选条件已重置')
}

// 处理分页变化
const handleSizeChange = (val) => {
  pageSize.value = val
  fetchExamList()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchExamList()
}

// 处理考试点击
const handleExamClick = (exam) => {
  router.push({
    path: `/student/prepareExam`,
    query: {
      examId: exam.id
    },
  })
}

// 获取考试列表
const fetchExamList = async () => {
  try {
    // 确保分页参数正确
    filters.pageNum = currentPage.value
    filters.pageSize = pageSize.value

    const res = await getGradeExamList(filters)

    if (res && res.data) {
      examList.value = res.data.records || []
      total.value = res.data.total || 0
      totalPages.value = Math.ceil(total.value / pageSize.value)
      // 更新页码显示
      updatePageNumbers()
    }
  } catch (error) {
    console.error('获取考试列表失败:', error)
    ElMessage.error('获取考试列表失败')
    examList.value = []
  }
}

// 更新页码显示
const updatePageNumbers = () => {
  const maxVisible = 5
  const pages = []

  if (totalPages.value <= maxVisible) {
    // 总页数小于等于最大显示页数，显示所有页码
    for (let i = 1; i <= totalPages.value; i++) {
      pages.push(i)
    }
  } else {
    // 总页数大于最大显示页数，显示部分页码
    if (currentPage.value <= 3) {
      // 当前页靠前，显示1,2,3,4,...,totalPages
      for (let i = 1; i <= 4; i++) {
        pages.push(i)
      }
      pages.push('...')
      pages.push(totalPages.value)
    } else if (currentPage.value >= totalPages.value - 2) {
      // 当前页靠后，显示1,...,totalPages-3,totalPages-2,totalPages-1,totalPages
      pages.push(1)
      pages.push('...')
      for (let i = totalPages.value - 3; i <= totalPages.value; i++) {
        pages.push(i)
      }
    } else {
      // 当前页在中间，显示1,...,currentPage-1,currentPage,currentPage+1,...,totalPages
      pages.push(1)
      pages.push('...')
      for (let i = currentPage.value - 1; i <= currentPage.value + 1; i++) {
        pages.push(i)
      }
      pages.push('...')
      pages.push(totalPages.value)
    }
  }

  pageNumbers.value = pages
}

// 处理跳转到指定页
const handleJumpPage = () => {
  if (jumpPage.value > 0 && jumpPage.value <= totalPages.value) {
    currentPage.value = jumpPage.value
    fetchExamList()
  } else {
    ElMessage.warning(`请输入1-${totalPages.value}之间的页码`)
    jumpPage.value = currentPage.value
  }
}

// 监听筛选条件变化
watch(
  [filters],
  () => {
    currentPage.value = 1
    fetchExamList()
  },
  { deep: true }
)

onMounted(() => {
  fetchExamList()
})
</script>

<style lang="less" scoped>
.el-pagination {
  --el-pagination-hover-color: var(--el-color-primary);
}
</style>
